
import os
from flask import render_template,flash,request,redirect,jsonify,session,url_for,send_from_directory
from flask_admin import Admin, BaseView, expose
from flask_babelex import Babel
import json
from werkzeug import secure_filename
from flask_login import login_required, current_user,login_user,logout_user
from .login import *
from .model import *
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif','mp4'])
#from wtforms import Form,TextField,PasswordField,validators



def init_views(app):
	#测试用
	@app.route('/',methods=['GET','POST'])
	def index():
		if request.method=="POST":
			username1=request.form['name']
			password1=request.form['pw']
			user=UserL.query.filter_by(userl_name=username1).one()
			login_user(user)
			print(current_user.id)
			u = UserL.query.filter_by(userl_name=username1,userl_password=password1).first()
			if(u):
				return render_template('note.html')
		#return render_template('index.html')
		return render_template('login.html')
		
	#添加分类	
	@app.route('/add',methods=['GET','POST'])
	def add():
		if request.method=="POST":
			title = request.form['title']
			addClassify(title)
			y=getAllClassify(current_user.userl_name)
			print(y)
			return render_template('add.html',var=y)
		y=getAllClassify(current_user.userl_name)
		return render_template('add.html',var=y)
	
	#删除分类以及分类下的所有内容
	@app.route('/delete/',methods=['GET','POST'])
	def delete():
		id = request.values.get('id')
		print(id)
		deleteclassfy(id)
		y=getAllClassify(current_user.userl_name)
		return render_template('add.html',var=y)
	#修改分类
	@app.route('/change/',methods=['GET','POST'])
	def change():
		id = request.values.get('id')
		title= request.values.get('title')
		if request.method=="POST":
			title = request.form['title']
			changeclassify(id,title)
			return redirect('/add')
		return render_template('change.html',var=title)
		
	#查看分类内容
	@app.route('/data/',methods=['GET','POST'])
	def data():
		id = request.values.get('id')
		y=getdata(id)
		if(y):
			return render_template('data.html',var=y)
		return "此分类无内容"
	#添加文章
	@app.route('/contenta',methods=['GET','POST'])
	def contenta():
		y=getAllClassify(current_user.userl_name)
		if request.method=="POST":
			title = request.form['title']
			id = request.form['id']
			print(id)
			content=request.form['content']
			print(content)
			addcontent(title,id,content)
			return "添加成功"
			
		return render_template('contenta.html',var=y)
	#修改文章内容
	@app.route('/changedata/',methods=['GET','POST'])
	def changedata():
		id = request.values.get('id')
		print("id......")
		print(id)
		x,y=datachange(id)
		print(x)
		print(y)


		if request.method=="POST":
			title = request.form['title']
			classify = request.form['classify']
			content = request.form['content']
			dataa(title,classify,content)
			
			return "修改成功"
		return render_template('changecontent.html',var=x,data=y)
		#return "过了"		
	
	#################################################################
		
	@app.route("/user",methods=['GET','POST'])
	def login():
		#myForm = LoginForm(request.form)
		if request.method=='POST':
			username = request.form['username']
			password = request.form['password']
			print(username)
			#u = User(myForm.username.data,myForm.password.data)
			u = UserL(username,password)
			
			if (u.isExisted()):
				
				session['username']=username
				return "登录成功"
			else:
				message=username
				#return render_template('index.html', message=message,form=myForm)
				return jsonify({'error':message})
		if request.method=='GET':
			#?username=xxx&password=xxxx
			username=request.values.get('username');
			password=request.values.get('password');
			u = UserL
			if (u.isExisted(username,password)):
				print(username)
				#login_user()
				user=UserL.query.filter_by(userl_name=username).one()
				login_user(user)
				#session['userid'] = username
				print(username)
				return "登录成功"
			else:
				message="username or password falut"
				#return render_template('index.html', message=message,form=myForm)
				return jsonify({'error':message})
		return jsonify({'data':请登录})

	@app.route("/loginout")
	def loginout():
		logout_user()
		return jsonify({'data':'logout successful'})

	#注册
	@app.route("/register", methods=['GET','POST'])
	def register():
		if request.method=='GET':
				#?username=xxx&password=xxxx
				username=request.values.get('username');
				password=request.values.get('password');
				u = User(username,password)
				if (u.add()==0):
					return "注册成功"
				else:
					message="register falut"
					#return render_template('index.html', message=message,form=myForm)
					return jsonify({'error':message})
		return jsonify({'data':'please first register'})
		

	@app.route("/jsondata",methods=['GET','POST'])
	@login_required
	def jsondata():
		l=getAllcontent()
		data=[]
		for i in l:
			tem={}
			tem['author']='%s' % i.author
			
			tem['content']='%s' % i.content
			data.append(tem)
		return jsonify({'status': data})


	@app.route("/test")
	@login_required
	def test():
		return render_template('test.html')
		
		
	#输出账户目录
	@app.route("/getClassify/<Userl>",methods=['GET','POST'])
	def getClassify(Userl):
		#if 'username' not in session:
			#return jsonify({'data':'please login'})
		
		l=getAllclassify(Userl)
		return jsonify({'data':l,'status': 200})
		
	#输出目录内容	
	@app.route("/getClassify/content/<id>",methods=['GET','POST'])
	def content(id):
		
		l=getcontent(id)
		data=[]
		
		for i in l:
			tem={}
			tem['id']='%s' % i.content_id
			
			tem['title']='%s' % i.content_title
			tem['content']='%s' %i.content_content
			
			data.append(tem)
		return jsonify({'status':data})

	#退出
	#@app.route("/loginout",methods=['GET','POST'])
	#def loginout():
		#session.pop('username', None)
		#return jsonify({'data':'loginout ok!'})
		
	#@app.errorhandler(404)
	#def page_not_found(error):
		#return jsonify({'status':404,'error':'please login first'})



		
		
	#检查用户名
	def allowed_file(filename):
		return '.' in filename and \
			   filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS 
			
	html = '''
		<!DOCTYPE html>
		<title>Upload File</title>
		<h1>图片上传</h1>
		<video src="http://172.20.162.201:8000/static/images/video2.mp4" controls="controls">
		</video>
		<form method=post enctype=multipart/form-data>
			 <input type=file name=file>
			 <input type=submit value=上传>
		</form>
		'''
	#@app.route('/uploads/<filename>')
	#def uploaded_file(filename):
		#return send_from_directory(app.config['UPLOAD_FOLDER'],filename)


	#图片上传			
	@app.route('/upload', methods=['GET', 'POST'])
	def upload_file():
		if request.method == 'POST':
			file = request.files['files']
			print(file)
			if file and allowed_file(file.filename):
				filename = secure_filename(file.filename)
				file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
				file_url = url_for('static', filename='images/'+file.filename)
				print(file_url)
				#res =  Response(file_url)
				#res.headers["ContentType"] = "text/html"
				#res.headers["Charset"] = "utf-8"
				#return html + '<br><img src=' + file_url + '>'
				return jsonify({'errno': 0,'data':'http://172.20.162.201:8000'+file_url})
				#return res
		return html
	


	babel = Babel(app)
	app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'


	admin = Admin(app, '后台管理', index_view=MyAdminIndexView(), base_template='my_master.html')	
	admin.add_view(UserlModelview(db.session,name=u'用户管理'))
	admin.add_view(ClassifyModelview(db.session, name=u'分类管理'))
	admin.add_view(MessageAdmin(db.session, name=u'文章管理'))



	
